package com.airspyar;

import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;


public class ObserverDataHolder {
	private final LocationManager locationManager;
	private final SensorManager sensorManager;
	private final SensorListener sensorListener;
	private final LocationListener locationListener;
	private boolean initialized=false;
	
	public ObserverDataHolder(LocationManager locationManager, SensorManager sensorManager){
		this.locationManager=locationManager;
		this.sensorManager=sensorManager;
		sensorListener=new SensorListener();
		locationListener=new LocationListener();
	}
	
	public synchronized boolean isInitialized(){
			return initialized;
	}
	
	public synchronized void initialize(){		
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationListener);
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this.locationListener);

		sensorManager.registerListener(this.sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
		sensorManager.registerListener(this.sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
		
		
		initialized=true;
	}
	
	public synchronized void release(){
		sensorManager.unregisterListener(this.sensorListener);

		locationManager.removeUpdates(this.locationListener);
		

		initialized=false;
	}
	
	public Location getLocation(){
		Location location=locationListener.getLocation();
		if(location==null){
			Location gpsLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			Location networkLocation=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			
			location=LocationListener.isBetterLocation(networkLocation, gpsLocation)?networkLocation : gpsLocation;
		}

		if(location==null)
			return null;
		
		if(!location.hasAltitude())
			location.setAltitude(100);
		
		return location;
	}
	
	public SimpleLocation getSimpleLocation(){
		Location location=this.getLocation();
		if(location==null)
			return null;
		
		return new SimpleLocation((float)location.getLatitude(), (float)location.getLongitude(), (float)location.getAltitude()/1000f);
	}
	
	public Vector3d getOrientationVector(){
		return sensorListener.getOrientationVector();
	}
}
